package com.jspgou.common.web;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 执行时间过滤器
 * 
 * @author liufang
 * 
 */
public class ProcessTimeFilter implements Filter {
	protected final Logger log = LoggerFactory
	         .getLogger(ProcessTimeFilter.class);
	/**
	 * 请求执行开始时间
	 */
	public static final String START_TIME = "_start_time";

    public void destroy(){
    }

    public void doFilter(ServletRequest req, ServletResponse res, 
    		FilterChain chain)throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest)req;
        
        //*强制转换response类型
        HttpServletResponse response=(HttpServletResponse)res;
        long time = System.currentTimeMillis();
        request.setAttribute("_start_time", Long.valueOf(time));
        
        //*将商品id加入cookie
/*        String goodId=request.getParameter("goodId");
        Cookie goodCookie=CookieUtils.getCookie(request, "goods");
        String goods=null;
        if(goodCookie!=null){
        	goods=goodCookie.getValue();
        }
        if(goods!=null){
        	String[] goodArr=goods.split(",");
        	Set<String> goodSet=new LinkedHashSet<String>(Arrays.asList(goodArr));
        	goodSet.add(goodId);
        	goods=goodSet.toString();
        	goods=goods.substring(1, goods.length()-1);
        }else{
        	goods=goodId;
        }
        Cookie browseGoods=new Cookie("browseGoods", goods);
        browseGoods.setMaxAge(1*60*60);
        response.addCookie(browseGoods);*/

        
        chain.doFilter(request, response);
        time = System.currentTimeMillis() - time;
		log.debug("process in {} ms: {}", time, request.getRequestURI());
    }

	public void init(FilterConfig arg0) throws ServletException {
	}
}
